/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cloudsimExamples;

/*
 * Title:        CloudSim Toolkit
 * Description:  CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation
 *               of Clouds
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 *
 * Copyright (c) 2009, The University of Melbourne, Australia
 */

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;

import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletSchedulerTimeShared;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterBroker;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.UtilizationModel;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicySimple;
import org.cloudbus.cloudsim.VmSchedulerTimeShared;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.provisioners.BwProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;

/**
 * An example showing how to create simulation entities
 * (a DatacenterBroker in this example) in run-time using
 * a globar manager entity (GlobalBroker).
 */
public class Model {
        public static final int NOTIFICATION = 0;
        public static final int MESSAGE = 1;
        public static final int LOG = 2;
        public static final double LATENCY = 1;
        public static final double PROCESS_MESSAGE = 1;
        public static final double PROCESS_NOTIFICATION = 0;
        public static final double FIRST_NOTIFY = 1;
        public static final double NEXT_NOTIFY = 1;
        public static final double END_NOTIFY = 0;

	public static void main(String[] args) {
		Log.printLine("Starting CloudSimExample8...");

		try {
			// First step: Initialize the CloudSim package. It should be called
			// before creating any entities.
			int num_user = 2;   // number of grid users
			Calendar calendar = Calendar.getInstance();
			boolean trace_flag = false;  // mean trace events

			// Initialize the CloudSim library
			CloudSim.init(num_user, calendar, trace_flag);

                        
                        
                        
			Notifier notifier = new Notifier("notifier");
                        Node pub = new Node("publisher");
                        Node sub = new Node("subscriber");
                        
                        FirstNotification fnot = new FirstNotification(0);
                        fnot.addNode(pub);
                        fnot.message="0";
                        fnot.time=0;
                        List<FirstNotification> fnots = new ArrayList<FirstNotification>();
                        fnots.add(fnot);
                        notifier.setList(fnots);
                        
                        Notification pnot = new Notification(0);
                        pnot.addNode(sub);
                        pub.addNotification(pnot);
                        
                        
                        

			// Second step: Create Datacenters
			//Datacenters are the resource providers in CloudSim. We need at list one of them to run a CloudSim simulation
			Datacenter datacenter0 = createDatacenter("Datacenter");

			//Third step: Create Broker
			DatacenterBroker broker = createBroker("Broker_0");
			int brokerId = broker.getId();

			//Fourth step: Create VMs and Cloudlets and send them to broke

			// Fifth step: Starts the simulation
			CloudSim.startSimulation();

			// Final step: Print results when simulation is over
			//List<Cloudlet> newList = broker.getCloudletReceivedList();
			//newList.addAll(globalBroker.getBroker().getCloudletReceivedList());

			CloudSim.stopSimulation();

			//printCloudletList(newList);

			//Print the debt of each user to each datacenter

			Log.printLine("CloudSimExample8 finished!");
		}
		catch (Exception e)
		{
			e.printStackTrace();
			Log.printLine("Unwanted errors happen");
		}
	}

	private static synchronized Datacenter createDatacenter(String name){

		// Here are the steps needed to create a PowerDatacenter:
		// 1. We need to create a list to store one or more
		//    Machines
		List<Host> hostList = new ArrayList<Host>();

		// 2. A Machine contains one or more PEs or CPUs/Cores. Therefore, should
		//    create a list to store these PEs before creating
		//    a Machine.
		List<Pe> peList1 = new ArrayList<Pe>();

		int mips = 1000;

		// 3. Create PEs and add these into the list.
		//for a quad-core machine, a list of 4 PEs is required:
		peList1.add(new Pe(0, new PeProvisionerSimple(mips))); // need to store Pe id and MIPS Rating
		peList1.add(new Pe(1, new PeProvisionerSimple(mips)));
		peList1.add(new Pe(2, new PeProvisionerSimple(mips)));
		peList1.add(new Pe(3, new PeProvisionerSimple(mips)));

		//Another list, for a dual-core machine
		List<Pe> peList2 = new ArrayList<Pe>();

		peList2.add(new Pe(0, new PeProvisionerSimple(mips)));
		peList2.add(new Pe(1, new PeProvisionerSimple(mips)));

		//4. Create Hosts with its id and list of PEs and add them to the list of machines
		int hostId=0;
		int ram = 16384; //host memory (MB)
		long storage = 1000000; //host storage
		int bw = 10000;

		hostList.add(
    			new Host(
    				hostId,
    				new RamProvisionerSimple(ram),
    				new BwProvisionerSimple(bw),
    				storage,
    				peList1,
    				new VmSchedulerTimeShared(peList1)
    			)
    		); // This is our first machine

		hostId++;

		hostList.add(
    			new Host(
    				hostId,
    				new RamProvisionerSimple(ram),
    				new BwProvisionerSimple(bw),
    				storage,
    				peList2,
    				new VmSchedulerTimeShared(peList2)
    			)
    		); // Second machine

		// 5. Create a DatacenterCharacteristics object that stores the
		//    properties of a data center: architecture, OS, list of
		//    Machines, allocation policy: time- or space-shared, time zone
		//    and its price (G$/Pe time unit).
		String arch = "x86";      // system architecture
		String os = "Linux";          // operating system
		String vmm = "Xen";
		double time_zone = 10.0;         // time zone this resource located
		double cost = 3.0;              // the cost of using processing in this resource
		double costPerMem = 0.05;		// the cost of using memory in this resource
		double costPerStorage = 0.1;	// the cost of using storage in this resource
		double costPerBw = 0.1;			// the cost of using bw in this resource
		LinkedList<Storage> storageList = new LinkedList<Storage>();	//we are not adding SAN devices by now

		DatacenterCharacteristics characteristics = new DatacenterCharacteristics(
                arch, os, vmm, hostList, time_zone, cost, costPerMem, costPerStorage, costPerBw);


		// 6. Finally, we need to create a PowerDatacenter object.
		Datacenter datacenter = null;
		try {
			datacenter = new Datacenter(name, characteristics, new VmAllocationPolicySimple(hostList), storageList, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return datacenter;
	}

	//We strongly encourage users to develop their own broker policies, to submit vms and cloudlets according
	//to the specific rules of the simulated scenario
	private static synchronized DatacenterBroker createBroker(String name){

		DatacenterBroker broker = null;
		try {
			broker = new DatacenterBroker(name);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return broker;
	}

	/**
	 * Prints the Cloudlet objects
	 * @param list  list of Cloudlets
	 */
	private static void printCloudletList(List<Cloudlet> list) {
		int size = list.size();
		Cloudlet cloudlet;

		String indent = "    ";
		Log.printLine();
		Log.printLine("========== OUTPUT ==========");
		Log.printLine("Cloudlet ID" + indent + "STATUS" + indent +
				"Data center ID" + indent + "VM ID" + indent + indent + "Time" + indent + "Start Time" + indent + "Finish Time");

		DecimalFormat dft = new DecimalFormat("###.##");
		for (int i = 0; i < size; i++) {
			cloudlet = list.get(i);
			Log.print(indent + cloudlet.getCloudletId() + indent + indent);

			if (cloudlet.getCloudletStatus() == Cloudlet.SUCCESS){
				Log.print("SUCCESS");

				Log.printLine( indent + indent + cloudlet.getResourceId() + indent + indent + indent + cloudlet.getVmId() +
						indent + indent + indent + dft.format(cloudlet.getActualCPUTime()) +
						indent + indent + dft.format(cloudlet.getExecStartTime())+ indent + indent + indent + dft.format(cloudlet.getFinishTime()));
			}
		}

	}
        
  // ----------------------notification------------------------
        public static class Notification{
            int id;
            List<Node> nodes = new ArrayList<Node>();
            String message = "";

        public Notification(int id) {
            this.id = id;
        }

        public List<Node> getNodes() {
            return nodes;
        }

        public void setNodes(List<Node> nodes) {
            this.nodes = nodes;
        }
        
        public void addNode(Node node) {
            nodes.add(node);
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getId() {
            return id;
        }
            
            
        }
        
        public static class FirstNotification extends Notification{

        double time = 0;    
        public FirstNotification(int id) {
            super(id);
        }

        public double getTime() {
            return time;
        }

        public void setTime(double time) {
            this.time = time;
        }
        
            
        }
        
        
        
  //--------------------notifier-------------------------------------------------------      
        public static class Notifier extends SimEntity{
            List<FirstNotification> list = new ArrayList<FirstNotification>();
            
        public Notifier(String name) {
            super(name);
        }

        @Override
        public void startEntity() {
            for(FirstNotification n:list){
                for(Node s:n.getNodes()){
                    schedule(s.getName(),n.getTime(),NOTIFICATION,n.message);
                }
            }
        }

        @Override
        public void processEvent(SimEvent ev) {
            Log.printLine(CloudSim.clock()+":notifier received event tag="+ev.getTag()+" from="+ev.getSource());
            
        }

        @Override
        public void shutdownEntity() {
            
        }

        public List<FirstNotification> getList() {
            return list;
        }

        public void setList(List<FirstNotification> list) {
            this.list = list;
        }
        
        public void addFirstNotification(FirstNotification n){
            list.add(n);
        }
            
        }
//---------------------------------------------node-----------------------------------------        
        public static class Node extends SimEntity{
            double free=0; // time when node will be free to process next task
            int messages = 0; //number of messages stored in memory
            int maxMessages = 0; // maximum of messages the node has in memory during simulation
            List<Notification> list = new ArrayList<Notification>();

        public Node(String name) {
            super(name);
        }

        @Override
        public void startEntity() {
            
        }

        @Override
        public void processEvent(SimEvent ev) {
            String message = (String)ev.getData();
            if (free<CloudSim.clock()){
               free = CloudSim.clock(); 
            }
            switch(ev.getTag()){
                
                case NOTIFICATION:        
                    Log.printLine(CloudSim.clock()+":"+this.getName()+" received notification "+message);
                    free += PROCESS_NOTIFICATION;
                    schedule(this.getId(),free - CloudSim.clock(),LOG, this.getName()+" processed notification "+message);
                    publish(Integer.parseInt(message),Integer.parseInt(message)+" message from "+this.getName());
                    break;
                case MESSAGE:
                    Log.printLine(CloudSim.clock()+":"+this.getName()+" received message "+message);
                    free += PROCESS_MESSAGE;
                    schedule(this.getId(), free - CloudSim.clock(),LOG, this.getName()+" processed message "+message);
                    publish(Integer.parseInt(message.substring(0, message.indexOf(' '))), message);
                    break;
                case LOG:
                    Log.printLine(CloudSim.clock()+":"+this.getName()+" "+message);
                    break;
                default:
                    Log.printLine(CloudSim.clock()+":"+this.getName()+" unknown tag from "+ev.getSource()+" with tag="+ev.getTag());
            }
        }

        @Override
        public void shutdownEntity() {
            
        }
        
        public void publish(int id, String m){
            Node sub = null;
            for(Notification n:list){
                if(n.getId()==id){
                    if(n.getNodes().size()>0){
                        Iterator<Node> iterator= n.getNodes().iterator();
                        sub = iterator.next();
                        free += FIRST_NOTIFY;
                        schedule(sub.getName(),free - CloudSim.clock()+LATENCY, MESSAGE, m);
                        schedule(this.getName(),free - CloudSim.clock(), LOG, this.getName()+" sent message to "+sub.getName()+" "+m);
                        while(iterator.hasNext()){
                            free += NEXT_NOTIFY;
                            sub = iterator.next();
                            schedule(sub.getName(),free - CloudSim.clock()+LATENCY, MESSAGE, m);
                            schedule(this.getName(),free - CloudSim.clock(), LOG, this.getName()+" sent message to "+sub.getName()+" "+m);
                        }
                        free += END_NOTIFY;
                    }
                }
            }
        }
        
        public void addNotification(Notification n){
            list.add(n);
        }
            
        }
        
        

}

